package com.pvj.myaccount.ui.summarize

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.content.res.ColorStateList
import android.graphics.Color
import android.icu.util.Calendar
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import android.widget.ProgressBar
import android.widget.RelativeLayout
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.pvj.myaccount.databinding.FragmentSummarizeBinding
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.uitls.TimeUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.util.Locale
import kotlin.random.Random


class SummarizeFragment : Fragment(), OnDateSetListener {
    private val TAG = "SlideshowFragment"

    private var _binding: FragmentSummarizeBinding? = null
    private lateinit var summarizeViewModel: SummarizeViewModel

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private var nowChooseYear: Int = 0// 当前选中年份（默认今年）


    val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        summarizeViewModel =
            ViewModelProvider(this)[SummarizeViewModel::class.java]

        _binding = FragmentSummarizeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val c: Calendar = Calendar.getInstance(Locale.CHINA)
        nowChooseYear = c.get(Calendar.YEAR)
        setTextYear(nowChooseYear)

        _binding!!.yearTv.setOnClickListener {
            onYearClick()
        }

        summarizeViewModel.yearList.observe(viewLifecycleOwner) {
            // 更新UI
            updateUI(it)
        }

        return root
    }

    @SuppressLint("SetTextI18n")
    private fun updateUI(data: List<Cost>?) {
        // 更新列表、文本视图或其他UI组件
        var total = 0.0
        val monthMap: MutableMap<Int, Double> = HashMap() // 月 total
        val typeMap: MutableMap<String, Double> = HashMap() // type total

        if (data != null) {
            for (cost in data) {
                val costMonth = TimeUtil.timestampToBeijingMonth(cost.eventTime)
                Log.d("SummarizeFragment", "eventTime:${cost.eventTime} month:${costMonth}")
                total += cost.money

                var monthCost = monthMap[costMonth]
                if (monthCost == null) {
                    monthCost = 0.0
                }
                monthCost += cost.money
                monthMap[costMonth] = monthCost

                var typeCost = typeMap[cost.type]
                if (typeCost == null) {
                    typeCost = 0.0
                }
                typeCost += cost.money
                typeMap[cost.type] = typeCost
            }
        }


        setTypePieDataSet(typeMap)

        _binding!!.monthContainer.removeAllViews()

        for (i in 1..12) {
            var monthCost = monthMap[i]
            if (monthCost == null) {
                monthCost = 0.0
            }
            addViewToContainer(i,monthCost.toInt(),total.toInt())
        }

        _binding!!.totalTv.text= "￥${total.toInt()}"
    }

    private fun setTypePieDataSet(typeMap: MutableMap<String, Double>){
        // 添加数据
        // 使用forEach遍历map
        val dataEntries: ArrayList<PieEntry> = ArrayList()
        typeMap.forEach { (key, value) ->
            dataEntries.add(PieEntry(value.toFloat(), key))
        }

        val colorList = mutableListOf<Int>()
        if (dataEntries.isEmpty()){
            dataEntries.add(PieEntry(100f, " 无"))
            colorList.add(Color.GRAY)
        }

        val dataSet = PieDataSet(dataEntries, null)

        for (i in 1..dataEntries.size) {
            colorList.add(getRandomColor())

        }
        Log.d("SummarizeFragment", "colorList size:${colorList.size}")
        dataSet.colors = colorList

        val pieData = PieData(dataSet)
        pieData.setValueTextSize(14f)
        _binding!!.pieChart.data = pieData


        // 设置是否展示描述
        _binding!!.pieChart.description.isEnabled = false
        _binding!!.pieChart.isDrawHoleEnabled  = false

        // 设置动画
        _binding!!.pieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad)

        // 刷新图表
        _binding!!.pieChart.invalidate()
    }

    private fun getRandomColor(): Int {
        return Color.rgb(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
    }

    @SuppressLint("SetTextI18n")
    private fun addViewToContainer(month: Int, monthCost: Int, total: Int) {
        val layout = RelativeLayout(requireContext())
        layout.setPadding(20, 8, 20, 8)
        Log.d("SummarizeFragment", "addViewToContainer month:${month} monthCost:${monthCost}  total：${total}")
        val textView = AppCompatTextView(requireContext())
        textView.text = "${month}月"
        textView.layoutParams = LinearLayoutCompat.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        textView.setTextColor(Color.BLACK)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
        textView.gravity = Gravity.CENTER
        layout.addView(textView)

        val progressBar =
            ProgressBar(requireContext(), null, android.R.attr.progressBarStyleHorizontal).apply {
                val paramsProgress = RelativeLayout.LayoutParams(
                    500,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                )
                paramsProgress.addRule(RelativeLayout.CENTER_IN_PARENT)
                layoutParams = paramsProgress
                max = total
                progress = monthCost

                progressTintList = ColorStateList.valueOf(Color.BLUE)
                secondaryProgressTintList = ColorStateList.valueOf(Color.GRAY)
            }
        layout.addView(progressBar)

        val moneyTv = AppCompatTextView(requireContext())
        moneyTv.text = "￥$monthCost"
        val paramsMoneyTv = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        paramsMoneyTv.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
        moneyTv.layoutParams = paramsMoneyTv
        moneyTv.setTextColor(Color.BLACK)
        moneyTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
        layout.addView(moneyTv)

        _binding!!.monthContainer.addView(layout)
    }


    /**
     * 年份选择器触发显示
     * @param v
     */
    private fun onYearClick() {
        // 显示选择器
        val datePickerDialog = DatePickerDialog(
            requireContext(),
            DatePickerDialog.THEME_HOLO_LIGHT,
            this,
            nowChooseYear,
            1,
            1
        )
        val datePicker = datePickerDialog.datePicker
        ((datePicker.getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(1).visibility =
            View.GONE // 隐藏月份
        ((datePicker.getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(2).visibility =
            View.GONE // 隐藏日
        datePickerDialog.show()
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume...")
        onYearUpdate(nowChooseYear)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }


    private fun onYearUpdate(year: Int) {
        summarizeViewModel.loadYearDataAsync(year)
    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        setTextYear(year) // 更新文本标签
        nowChooseYear = year // 更新选中选项
        onYearUpdate(year)
    }

    private fun setTextYear(year: Int) {
        _binding!!.yearTv.text = StringBuilder().append(year).toString() // 更新文本标签
    }
}